package com.movie.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movie.datacomm.common.CommResp;
import com.movie.datacomm.model.Movie;
import com.movie.datacomm.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("movie")
public class MovieController {

    @Autowired
    MovieService movieService;


    @RequestMapping(value = "/getCurrentPageMovie", method = RequestMethod.GET)
    @ResponseBody
    public CommResp getCurrentPageMovie(int currentPage, int pageSize, @Nullable String input){

        Page<Movie> page = new Page<>(currentPage, pageSize);

        QueryWrapper<Movie> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(input)){
            wrapper.like("name", input);
        }
        wrapper.orderByAsc("movie_id");

        page = movieService.page(page, wrapper);
        return CommResp.okList(page.getRecords(), page.getTotal());
    }

    @RequestMapping(value = "/updateMovieInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommResp updateMovieInfo(@RequestBody Movie movie){
        Movie tmpMovie = movieService.getOne(new QueryWrapper<Movie>().eq("name", movie.getName()).le(false, "movie_id", movie.getMovieId()));
        if(null != tmpMovie){
            return CommResp.fail("电影名已存在");
        }

        boolean result = movieService.updateById(movie);
        if(result) {
            return CommResp.ok();
        }else{
            return CommResp.fail("更新失败");
        }
    }

    @RequestMapping(value = "/addMovieInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommResp addMovieInfo(@RequestBody Movie movie){
        Movie tmpMovie = movieService.getOne(new QueryWrapper<Movie>().eq("name", movie.getName()));
        if(null != tmpMovie){
            return CommResp.fail("电影名已存在");
        }

        boolean result = movieService.save(movie);
        if(result) {
            return CommResp.ok();
        }else{
            return CommResp.fail("操作失败");
        }
    }

    @RequestMapping(value = "/deleteMovieInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommResp deleteMovieInfo(@RequestBody Movie movie){

        boolean result = movieService.removeById(movie.getMovieId());
        if(result) {
            return CommResp.ok();
        }else{
            return CommResp.fail("删除失败");
        }
    }

}
